package com.yang.job.infra.event;


import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class EventCenter {
    private EventBus eventBus = new EventBus();

    private AsyncEventBus asyncEventBus;

    private ExecutorService asyncEventExecutorService;

    private static Map<String, IEventHandler> eventHandlerMap = new ConcurrentHashMap<>();

    public EventCenter(ExecutorService executorService) {
        this.asyncEventExecutorService = executorService;
        asyncEventBus = new AsyncEventBus(executorService);
    }

    public void postEvent(IEvent iEvent) {
        String eventClassName = iEvent.getClass().getName();
        IEventHandler iEventHandler = eventHandlerMap.get(eventClassName);
        eventBus.register(iEventHandler);
        eventBus.post(iEvent);
    }

    public void asyncPostEvent(IEvent iEvent) {
        String eventClassName = iEvent.getClass().getName();
        IEventHandler iEventHandler = eventHandlerMap.get(eventClassName);
        asyncEventBus.register(iEventHandler);
        asyncEventBus.post(iEvent);
    }

    public void shutdown() {
        if (this.asyncEventExecutorService == null) {
            return;
        }
        if (!asyncEventExecutorService.isShutdown()) {
            asyncEventExecutorService.shutdown();
            try {
                if (!asyncEventExecutorService.awaitTermination(10, TimeUnit.SECONDS)) {
                    asyncEventExecutorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void registerEventHandler(String eventName, IEventHandler iEventHandler) {
        eventHandlerMap.put(eventName, iEventHandler);
    }
}

